package com.example.net.interceptor;

import java.io.IOException;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/21 14:57
 * 描述	      ${在body里面追加参数
 *                奇葩需求：将所有的get-->>post 将get后面的parms-->>post body}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class AppendBodyIntercepter implements Interceptor {
        //解析为json格式
        String APPLICATION_JSON = "application/json";
        //解析为原声form表单格式则为application/x-www-form-urlencoded
        String APPLICATION_FORM = "application/x-www-form-urlencoded";
        //提交数据为multipart/form-data
        String APPLICATION_FROM_DATA = "multipart/form-data";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //获取get请求的所有参数名称
        Set<String> strings = request.url().queryParameterNames();
        StringBuilder builder = new StringBuilder();
        for (String s:strings) {
            builder.append(s)
                    .append("=")
                    //查询url参数后面值
                    .append(request.url().queryParameter(s))
                    .append(",");
        }

        String body = builder.toString().substring(0, builder.toString().length() - 1);

        //创建requstBody病解析为json格式
        RequestBody requestBody = RequestBody.create(MediaType.parse(APPLICATION_JSON),body);

        Request newRequest = request.newBuilder().post(requestBody).build();
        return chain.proceed(newRequest);
    }
}
